<script lang="ts" setup>
import {
    createWeb3Modal,
    defaultConfig,
    useWeb3Modal,
    useWeb3ModalEvents,
    useWeb3ModalState,
    useWeb3ModalTheme
} from '@web3modal/ethers5/vue'
import { SiweMessage } from 'siwe'
import { createSIWEConfig } from '@web3modal/siwe'
import type { SIWECreateMessageArgs, SIWESession, SIWEVerifyMessageArgs } from '@web3modal/core'

// @ts-expect-error 1. Get projectId
const projectId = '84113507dea067e522655c58ddb66939'
if (!projectId) {
    throw new Error('VITE_PROJECT_ID is not set')
}

// 2. Set chains
const chains = [
    {
        chainId: 1,
        name: 'Ethereum',
        currency: 'ETH',
        explorerUrl: 'https://etherscan.io',
        rpcUrl: 'https://cloudflare-eth.com'
    },
    {
        chainId: 42161,
        name: 'Arbitrum',
        currency: 'ETH',
        explorerUrl: 'https://arbiscan.io',
        rpcUrl: 'https://arb1.arbitrum.io/rpc'
    }
]
const siweConfig = createSIWEConfig({
    createMessage: ({ nonce, address, chainId }: SIWECreateMessageArgs) =>
        new SiweMessage({
            version: '1',
            domain: window.location.host,
            uri: window.location.origin,
            address,
            chainId,
            nonce,
            // Human-readable ASCII assertion that the user will sign, and it must not contain `\n`.
            statement: 'Sign in With Ethereum.'
        }).prepareMessage(),
    getNonce: async () => {
        // Fetch nonce from your SIWE server
        const nonce = await "1312"
        if (!nonce) {
            throw new Error('Failed to get nonce!')
        }

        return nonce
    },
    getSession: async () => {
        // Fetch currently authenticated user
        const session = {  address:'', chainId: '' }
        if (!session) {
            throw new Error('Failed to get session!')
        }

        const { address, chainId } = session

        return { address, chainId }
    },
    verifyMessage: async ({ message, signature }: SIWEVerifyMessageArgs) => {
        try {
            // Use your SIWE server to verify if the message and the signature are valid
            // Your back-end will tipically rely on SiweMessage(message).validate(signature)
            const isValid = await Promise.resolve(true)
            return isValid
        } catch (error) {
            return false
        }
    },
    signOut: async () => {
        try {
            // Sign out by calling the relevant endpoint on your back-end
            await signOut()

            return true
        } catch (error) {
            return false
        }
    }
})
const ethersConfig = defaultConfig({
    metadata: {
        name: 'chainingview',
        description: 'Web3Modal chainingview',
        url: 'https://web3modal.com',
        icons: ['https://explorer-api.walletconnect.com/v3/logo/lg/dda0f0fb-34e8-4a57-dcea-b008e7d1ff00?projectId=2f05ae7f1116030fde2d36508f472bfb']
    },
    defaultChainId: 1,
    rpcUrl: 'https://cloudflare-eth.com'
})

// 3. Create modal
createWeb3Modal({
    siweConfig,
    ethersConfig,
    projectId,
    chains,
    themeMode: 'light',
    themeVariables: {
        '--w3m-color-mix': '#00BB7F',
        '--w3m-color-mix-strength': 20
    }
})

// 4. Use modal composable
const modal = useWeb3Modal()
const state = useWeb3ModalState()
const { setThemeMode, themeMode, themeVariables } = useWeb3ModalTheme()
const events = useWeb3ModalEvents()
</script>

<template>
    <w3m-button />
    <w3m-network-button />
    <w3m-connect-button />
    <w3m-account-button />

    <button @click="modal.open()">Open Connect Modal</button>
    <button @click="modal.open({ view: 'Networks' })">Open Network Modal</button>
    <button @click="setThemeMode(themeMode === 'dark' ? 'light' : 'dark')">Toggle Theme Mode</button>
    <pre>{{ JSON.stringify(state, null, 2) }}</pre>
    <pre>{{ JSON.stringify({ themeMode, themeVariables }, null, 2) }}</pre>
    <pre>{{ JSON.stringify(events, null, 2) }}</pre>
</template>